package com.scorpio.server.base;


import com.scorpio.server.inter.NetworkMsgObserver;
import com.scorpio.server.inter.TCPProtocol;
import com.scorpio.server.inter.TCPProtocolImpl;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * 基础的通讯服务
 * Created by BLACK on 2017/7/28.
 */
public abstract class BaseIMServer extends BaseServer implements NetworkMsgObserver, Runnable {
    // 超时时间，单位毫秒
    private static final int TimeOut = 3000;
    //选择器
    public Selector mSelector;
    private final TCPProtocol mTcpProtocol;

    public BaseIMServer(Selector mSelector) {
        this.mSelector = mSelector;
        mTcpProtocol = new TCPProtocolImpl(this);
    }

    @Override
    public void run() {
        while (true) {
            dispatchEvent();
        }
    }

    //selector事件分发
    private void dispatchEvent() {
        try {
            if (mSelector.select(TimeOut) == 0) return;
        } catch (IOException e) {
            e.printStackTrace();
        }
        Iterator<SelectionKey> keyIter = mSelector.selectedKeys().iterator();
        while (keyIter.hasNext()) {
            SelectionKey key = keyIter.next();
            if (key.isAcceptable()) {
                // 有客户端连接请求时
                mTcpProtocol.handleAccept(key);
            }
            if (key.isReadable()) {
                // 判断是否有数据发送过来
                mTcpProtocol.handleRead(key);
            }
            if (key.isValid() && key.isWritable()) {
                // 判断是否有效及可以发送给客户端
                mTcpProtocol.handleWrite(key);
            }
            // 移除处理过的键
            keyIter.remove();
        }
    }
}
